import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/users',
    name: 'UserManagement',
    component: () => import('../views/UserManagement.vue'),
    meta: { requiresAdmin: true }
  },
  {
    path: '/rooms',
    name: 'RoomManagement',
    component: () => import('../views/RoomManagement.vue'),
    meta: { requiresAdmin: true }
  },
  {
    path: '/reservations',
    name: 'ReservationManagement',
    component: () => import('../views/ReservationManagement.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/my-reservations',
    name: 'MyReservations',
    component: () => import('../views/MyReservations.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/new-reservation',
    name: 'NewReservation',
    component: () => import('../views/NewReservation.vue'),
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 获取最新的用户信息
const getCurrentUser = () => {
  try {
    const userStr = localStorage.getItem('user')
    return userStr ? JSON.parse(userStr) : null
  } catch (e) {
    console.error('解析用户信息失败:', e)
    localStorage.removeItem('user') // 清除无效的用户数据
    return null
  }
}

// 路由守卫
router.beforeEach((to, from, next) => {
  // 每次路由变化时获取最新的用户信息
  const user = getCurrentUser()
  
  console.log('路由守卫检查:', { 
    path: to.path, 
    user: user ? user.username : null,
    requiresAuth: to.meta.requiresAuth, 
    requiresAdmin: to.meta.requiresAdmin 
  })
  
  // 需要登录但未登录
  if (to.meta.requiresAuth && !user) {
    console.log('需要登录，重定向到登录页')
    next('/login')
  } 
  // 需要管理员权限但不是管理员
  else if (to.meta.requiresAdmin && (!user || user.role !== 'ADMIN')) {
    console.log('需要管理员权限，重定向到首页')
    next('/')
  } 
  // 正常通过
  else {
    next()
  }
})

export default router 